package server.java.autoduel.World;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.logging.Logger;

import com.thoughtworks.xstream.XStream;

/**
 * Provides a world blueprint for a fresh server start
 * 
 * @author Ian Axelrod
 * @author Liz Ha
 * @author Andrew Muldowney
 * @author Edward Futch
 */
public class WorldFactory {

	/**
	 * The {@link Logger} for this class.
	 */
	public static final Logger logger = Logger.getLogger(WorldFactory.class
			.getName());

	/**
	 * The relative path to the world file
	 */
	private final static String data_file = "/data/world/world.xml";

	/**
	 * This is the world that will be provided
	 */
	private static World world;

	/**
	 * Loads up the world from the server filesystem
	 * 
	 * @throws IOException
	 */
	public static void loadWorld(String currentDir) throws IOException {
		final File worldFile = new File(currentDir + WorldFactory.data_file);
		final FileInputStream reader = new FileInputStream(worldFile);
		final byte[] buf = new byte[(int) worldFile.length()];

		reader.read(buf);
		reader.close();
		final XStream xstream = new XStream();
		xstream.alias("World", World.class);
		WorldFactory.world = (World) xstream.fromXML(new String(buf));
		WorldFactory.logger.info("Loaded default World from xml: "
				+ WorldFactory.world.toString());
	}

	/**
	 * Provides the requested world to the caller
	 * 
	 * @return a copy of the requested world
	 */
	public static World provideWorld() {
		return WorldFactory.world.copy();
	}
}